package bsc.war.handler;

import bsc.ejb.entity.Map;
import bsc.ejb.entity.MapDrawingSettings;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.Pointer;
import bsc.ejb.entity.Project;
import bsc.ejb.entity.SRM;
import bsc.ejb.entity.ScoreCard;
import bsc.ejb.entity.ScoreDomain;
import bsc.ejb.entity.ScoreView;
import bsc.ejb.metadata.Colorimetry;
import bsc.ejb.metadata.Comparation;
import bsc.ejb.metadata.MapDrawing;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.Score;
import bsc.war.service.ScoreCardUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author castrosalazar
 */
public class MapFinalUser extends AbstractController {

    public MapFinalUser() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            ScoreDomain currentSD = (ScoreDomain) request.getSession().getAttribute("currentScoreDomain");
            //System.out.println("El dominio activo es: " + currentSD.getName());

            ScoreView currentView = currentSD.getScoreView();
            HttpSession session = request.getSession(true);
            Person person = (Person) session.getAttribute("person");
            //System.out.println("La vista activa es: " + currentView.getName());
            /*
            List<Map> mapList = delegate.findMap();
            List<Map> maps2remove = new LinkedList<Map>();
            for (Map tmp : mapList) {
                System.out.println("El ScoreView temp: " + tmp.getScoreview().getName());
                if (!tmp.getScoreview().equals(currentView)) {
                    System.out.println("Se va a quitar: " + tmp.getName());
                    maps2remove.add(tmp);
                }
            }
            for (Map tmp : maps2remove) {
                mapList.remove(tmp);
            }
            */
            List<Map> mapList = new ArrayList<Map>();
            mapList.add((Map)currentView.getScoreCard());
            
            //System.out.println("El tamaño de la lista es: " + mapList.size());
            request.setAttribute("mapList", mapList);

            List<SRM> srmList = delegate.findSRM();
            List<SRM> srms2remove = new LinkedList<SRM>();
            for (SRM tmp : srmList) {
                if (!tmp.getScoreView().equals(currentView)) {
                    srms2remove.add(tmp);
                }
            }
            for (SRM tmp : srms2remove) {
                srmList.remove(tmp);
            }
            request.setAttribute("srmList", srmList);

            List<Project> projectList = delegate.findProject(person);
            request.setAttribute("projectList", projectList);

            List<ScoreView> scoreViewList = new ArrayList<ScoreView>(); //delegate.findScoreView();
            scoreViewList.add(currentView);
            request.setAttribute("scoreViewList", scoreViewList);

            List<Comparation> comparationList = new ArrayList<Comparation>();
            List<Comparation> comparations = delegate.findComparation(delegate.findFramework(true), true);
            for (Comparation comparation : comparations) {
                if (comparation.getType() != comparation.getType().REAL) {
                    comparationList.add(comparation);
                }
            }
            request.setAttribute("comparationList", comparationList);

            Date date = ScoreCardUtils.getSystemDate(request);
            Comparation comparation = ScoreCardUtils.getSystemComparation(request);

            
            session.setAttribute("date", date);
            session.setAttribute("comparation", comparation);

            //System.out.println("El id del mapa es: " + request.getParameter("map"));

            Map currentMap = request.getParameter("map") != null ? delegate.findMap(Long.parseLong(request.getParameter("map"))) : mapList.get(0);
            request.setAttribute("currentMap", currentMap);

            //System.out.println("El mapa es: " + currentMap.getName());
            MapDrawing currentDrawing = currentMap.getMapDrawing();
            request.setAttribute("currentDrawing", currentDrawing);

            List<MapDrawingSettings> mapdrawingsettings = delegate.findMapDrawingSettings(currentDrawing);
            List<ScoreCard> semaphores = new ArrayList<ScoreCard>();
            java.util.Map<ScoreCard, Double> left = new HashMap<ScoreCard, Double>();
            java.util.Map<ScoreCard, Double> top = new HashMap<ScoreCard, Double>();
            java.util.Map<ScoreCard, Double> scores = new HashMap<ScoreCard, Double>();
            java.util.Map<ScoreCard, String> colors = new HashMap<ScoreCard, String>();
            java.util.Map<ScoreCard, List<ScoreCard>> children = new HashMap<ScoreCard, List<ScoreCard>>();
            for (MapDrawingSettings mapDrawingSetting : mapdrawingsettings) {
                ScoreCard scoreCard = mapDrawingSetting.getSettings().getScoreCard();
                semaphores.add(scoreCard);

                left.put(scoreCard, mapDrawingSetting.getX());
                top.put(scoreCard, mapDrawingSetting.getY());

                Score score = ScoreCardUtils.calculateScore(delegate, comparation, scoreCard, date);
                scores.put(scoreCard, score.getScore());
                //System.out.println("Scorecard score:"  + scoreCard.getName());
                //System.out.println("Score: " + score.getScore());
                Colorimetry colorimetry = delegate.findColorimetry(scoreCard, score.getScore());
                if(scoreCard instanceof Pointer){
                    if(!score.isOutOfDate()) {
                        // System.out.println("name: " + scoreCard.getName());
                        colors.put(scoreCard, colorimetry == null ? "" : colorimetry.getColor());
                    }
                } else {
                    colors.put(scoreCard, colorimetry == null ? "" : colorimetry.getColor());
                }

                List<ScoreCard> scoreChildren = delegate.findScoreCard(scoreCard);
                children.put(scoreCard, scoreChildren);
                for (ScoreCard sc : scoreChildren) {
                    Score childrenScore = ScoreCardUtils.calculateScore(delegate, comparation, sc, date);
                    Colorimetry tmpColor = delegate.findColorimetry(sc, childrenScore.getScore());
                    scores.put(sc, childrenScore.getScore());
                    if(sc instanceof Pointer){
                        if(!childrenScore.isOutOfDate()) {
                            colors.put(sc, tmpColor == null ? "" : tmpColor.getColor());
                        }
                    } else {
                        colors.put(sc, tmpColor == null ? "" : tmpColor.getColor());
                    }
                }
            }
            request.setAttribute("semaphores", semaphores);
            request.setAttribute("left", left);
            request.setAttribute("top", top);
            request.setAttribute("scores", scores);
            request.setAttribute("colors", colors);
            request.setAttribute("children", children);
        } catch (Exception e) {
            logger.error("Caught exception", e);
        }
        return new ModelAndView("mapFinalUser");
    }
}
